import chartOp from '@/common/chart-option.js';
import echartUtil from '@/components/common/echart/echart-util.js';
import {
  clone, getColor,
  getSerieColor, getThemeColors, isNum,
  numFormat,
  setExtraConfig,
  xssFilter,
  mergeColorBoard,
} from '@/utils/util';
import optionList from './chart-option.json';
import _colorBoard from './color_board';
const colorBoard = mergeColorBoard(_colorBoard);

const tooltip = {
  backgroundColor: '',
  seriesNameColor: '',
  valueColor: '',
};

/**
 * 设置图表数据 series legend等
 * @param {*} option 图表option
 * @param {*} data 图表数据
 * @param {*} property 配置页面中属性面板中的参数
 */
function setChartData(option, data, property) {
  const { xAxisData, seriesData } = data;
  const { componentStyle, legend, lineType, shadow, color } = property;

  const themeColors = getThemeColors(color, colorBoard[componentStyle].colorGroup);
  const colorGroupLength = themeColors.length;

  option.xAxis.data = xAxisData;
  seriesData.forEach((item, index) => {
    const serie = {
      type: 'line',
      connectNulls: true,
      name: item.name,
      data: item.data,
      symbol: 'circle',
      symbolSize: 6,
      smooth: lineType === 'fillet' ? true : false, // 线是否平滑
    };

    // 颜色套餐
    let colorValue;
    let _color;
    if (typeof color === 'string') {
      _color = themeColors[index % colorGroupLength];
      colorValue = getSerieColor(_color);
    } else {
      const { name } = item;
      _color = getColor(color, name);
      colorValue = getSerieColor(_color);
    }
    serie.itemStyle = { color: colorValue };

    // 区域填充样式
    if (shadow) {
      serie.areaStyle = {
        opacity: 0.3,
        global: false, // 缺省为 false
        color: {
          type: 'linear',
          x: 0,
          y: 1,
          x2: 0,
          y2: -0.2,
          colorStops: [
            { offset: 1, color: Array.isArray(_color) ? _color[0] : _color },
            { offset: 0, color: 'rgba(256, 256, 256, 0)' },
          ],
        },
      };
    }
    item.name && option.legend.data.push(item.name);
    option.series.push(serie);
  });

  // 有无图例
  if (!legend) {
    option.legend.show = false;
  }
}

/**
 * 自定义图表提示框
 * @param {*} params  echart自带参数
 */
function formateTooltip(params) {
  const isVisible = chartOp.isOrgTooltipVisible();
  if (!isVisible) {
    return '';
  }
  const { seriesNameColor } = tooltip;
  let formatStr_ = '<div style="padding:5px 7px">';
  params.forEach((item, index) => {
    xssFilter(item, ['axisValue', 'seriesName', 'value']);
    if (index === 0) {
      formatStr_ += `<span>${echartUtil.getXaxisValue(item)}</span><br/>`;
    }
    if (item.seriesName) {
      formatStr_ += `${item.marker} <span style='color:${seriesNameColor}'>${item.seriesName}:</span> ${numFormat(
        item.value[1],
        true,
      )}`;
    } else {
      formatStr_ += `${item.marker} ${numFormat(item.value[1], true)}`;
    }
    if (index !== params.length) {
      formatStr_ += '<br/>';
    }
  });
  formatStr_ += '<div/>';
  return formatStr_;
}

function convertDataHorizontal(data, configData, property) {
  if (!data.length) {
    return false;
  }

  const seriesData = [];
  const xAxisData = [];
  let count = { y: 0 };
  data.forEach(item => {
    if (!xAxisData.includes(item.x)) {
      xAxisData.push(item.x);
    }
    let y = 0;
    Object.keys(item).forEach(key => {
      if (key.includes('y')) {
        y++;
      }
    });
    count = { y: y > count.y ? y : count.y };
  });
  const dataObj = {};

  // 初始化数组
  for (let i = 0; i < count.y; i++) {
    const row = configData.tableData[i + 1];
    dataObj[`y${i}Data`] = {
      data: [],
      legendName: row?.legendName || `Serie_${i + 1}`,
      flag: false,
    };
  }

  for (let index = 0; index < xAxisData.length; index++) {
    const x = String(xAxisData[index]);
    const tempItem = data.find(d => String(d.x) === x);
    for (let i = 0; i < count.y; i++) {
      let temp = tempItem[`y${i + 1}`];
      if (property.emptyName !== 'tomographic') {
        temp = isNum(temp) ? Number(temp) : 0;
      }
      dataObj[`y${i}Data`].data.push([x, temp]);
    }
  }
  for (let i = 0; i < count.y; i++) {
    seriesData.push({
      yAxisIndex: 0,
      name: dataObj[`y${i}Data`].legendName,
      data: dataObj[`y${i}Data`].data,
      type: 'line',
    });
  }

  if (seriesData.length === 0) {
    return null;
  }
  return { xAxisData, seriesData };
}

function convertDataLongitudinal(data, configData, property) {
  if (data.length) {
    const seriesData = [];
    const xAxisData = [];
    let newData = [];
    const { seriesKey, xAxisKey } = chartOp.getXAxisKeyAndSeriesKey(data);

    if (seriesKey.length) {
      seriesKey.forEach(s => {
        xAxisKey.forEach(x => {
          const dataItem = data.find(d => String(d.x) === String(x) && String(d.s) === String(s));
          if (dataItem) {
            newData.push(dataItem);
          } else {
            newData.push({ x, s, y: null });
          }
        });
      });
    } else {
      newData = data;
    }

    for (let i = 0; i < newData.length; i++) {
      let { y } = newData[i];
      const { x, s } = newData[i];
      if (property.emptyName !== 'tomographic') {
        y = isNum(y) ? Number(y) : 0;
      }
      const isInclude = xAxisData.includes(x);
      if (!isInclude) {
        xAxisData.push(x);
      }

      const name = s || '';
      const item = seriesData.find(sData => String(sData.name) === String(name));
      if (item) {
        item.data.push([x, y]);
      } else {
        seriesData.push({ name, data: [[String(x), y]] });
      }
    }
    return { xAxisData, seriesData };
  } else {
    return null;
  }
}

/**
 * 设置图表整体option
 * @param {*} data 图表数据
 * @param {*} property 配置页面中属性面板中的参数
 * @param {*} configData 配置页面中数据面板中的参数
 */

/**
 * 将接口数据转换为echart方便使用的数据
 * @param {*} data 接口数据
 */
export const convertData = function(data, configData, property) {
  const { emptyDisp, echart } = property;
  const emptyName = echart ? echart.series._emptyName : emptyDisp;
  property.emptyName = emptyName;
  if (configData.dataMappingType === 'horizontalData') {
    return convertDataHorizontal(data, configData, property);
  } else {
    return convertDataLongitudinal(data, configData, property);
  }
};

export const setChartOption = (data, property, configData, extraConfig = {}) => {
  const { animation = true } = extraConfig;
  const { title, xAxisName = '', yAxisName, lineType, shadow, legend, componentStyle, size, position, color } = property;
  const { originTooltipSetting } = property.tooltip || {};
  tooltip.seriesNameColor = colorBoard[componentStyle].tooltip.seriesNameColor;

  const tooltipBgColor =
    (originTooltipSetting && originTooltipSetting.background) || colorBoard[componentStyle].tooltip.backgroundColor;

  const vars = {
    animation,
    componentStyle,
    xAxisName,
    colorBoard,
    property,
    formateTooltip,
    tooltipBgColor,
    xLabelRotate: property.xLabelRotate || 0,
  };
  let option = clone(optionList);
  option = chartOp.parseJsonOption(option, vars);

  chartOp.setDataZoom('uniaxial-line', { option, data, property, colorBoard });
  setChartData(option, data, property);
  chartOp.setYAxisName('uniaxial-line', { option, property, colorBoard });
  chartOp.setMarkLine('uniaxial-line', { option, property, configData, colorBoard });

  const extraConfigKeyLength = Object.keys(extraConfig).length;
  if (extraConfigKeyLength) {
    setExtraConfig(option, extraConfig);
  }

  // 附加公共配置
  option = chartOp.mergeOption(option, property);
  return option;
};
